package com.smart.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.smart.admin.config.AliyunOssProperties;
import com.smart.admin.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.Date;


@Service
public class UploadServiceImpl implements UploadService {
    public static final String CONSTANT_DATE_FORMAT1 = "yyyy/MM/dd";
    public static final String CONSTANT_DATE_FORMAT = "yyyyMMddHHmmss";

    @Resource
    private OSS ossClient;
    @Resource
    private AliyunOssProperties properties;

    @Override
    public String uploadAliOss(MultipartFile file) throws IOException {
        // 获取文件原名称
        String originalFilename = file.getOriginalFilename();
        // 获取文件类型
        assert originalFilename != null;
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 新文件名称
        // 构建日期路径, 例如：OSS目标文件夹/2021/07/21/文件名
        String fileName = String.format("%s%s/%s%s",
                properties.getFileHost(),
                DateUtil.format(new Date(), CONSTANT_DATE_FORMAT1),
                DateUtil.format(new Date(), CONSTANT_DATE_FORMAT),
                fileType
        );
        //       调用oss的putObject方法实现上传
        // 第一个参数 Bucket名称
        // 第二个参数，上传到oss文件路径和文件名称   A/B/图片.jpg
        // 第三个参数，上传文件输入流
        PutObjectResult result = ossClient.putObject(properties.getBucketName(), fileName, file.getInputStream());
        String singeNatureUrl = getSingeNatureUrl(fileName, 60 * 60);
        // 关闭OSSClient。
        // 访问路径
        // https://BucketName.Endpoint/ObjectName
        return singeNatureUrl;
    }

    public String getSingeNatureUrl(String filename, int expSeconds) {
        Date expiration = new Date(System.currentTimeMillis() + expSeconds * 1000L);
        URL url = ossClient.generatePresignedUrl(properties.getBucketName(), filename, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}
